<template>
  <div class="schedule-page">
    <div class="schedule-container">
      <h1>课程表</h1>
      
      <div class="content-wrapper">
        <div class="course-menu">
          <div v-for="(course, index) in courses" 
               :key="index"
               :style="{ backgroundColor: course.color }"
               class="course-item"
               draggable="true"
               @dragstart="dragStart($event, course)"
               @touchstart="touchStart($event, course)">
            {{ course.name }}
          </div>
        </div>

        <div class="schedule-area">
          <div class="schedule-wrapper">
            <div id="schedule-content">
              <el-table :data="schedule" 
                       class="schedule-table" 
                       :row-class-name="rowClassName">
                <el-table-column prop="time" 
                                label="时间/星期" 
                                width="100">
                </el-table-column>
                <el-table-column v-for="day in days" 
                                :key="day" 
                                :label="day" 
                                align="top" 
                                class-name="is-top">
                  <template #default="scope">
                    <div class="schedule-cell"
                         :data-day="day"
                         :data-time="scope.row.time"
                         @drop="onDrop($event, scope.row, day)"
                         @dragover="onDragOver($event)"
                         @dragenter="onDragEnter($event)"
                         @dragleave="onDragLeave($event)"
                         @touchmove="touchMove($event)"
                         @touchend="touchEnd($event, scope.row, day)">
                      <div v-for="(course, index) in scope.row[day]" 
                           :key="index"
                           class="course"
                           :style="{ backgroundColor: course.color }"
                           draggable="true"
                           @dragstart="dragStart($event, course, scope.row, day, index)"
                           @touchstart="touchStart($event, course, scope.row, day, index)"
                           @dragenter.stop="onDragEnterCourse($event)"
                           @dragleave.stop="onDragLeaveCourse($event)"
                           @dragover.stop="onDragOverCourse($event)"
                           @drop.stop="onDropCourse($event, scope.row, day, index)">
                        {{ course.name }}
                      </div>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>

          <div class="button-group">
            <el-button type="primary" @click="downloadSchedule">
              <el-icon><Download /></el-icon>
              下载课程表
            </el-button>
            <el-button type="danger" @click="clearSchedule">
              <el-icon><Delete /></el-icon>
              清空课程表
            </el-button>
            <el-button type="warning" @click="goToHomepage">
              <el-icon><Back /></el-icon>
              返回
            </el-button>
          </div>
        </div>
      </div>

      <div class="notes">
        <h3>帮助说明：</h3>
        <ul>
          <li>左侧为课程列表，可拖拽到右侧课程表中</li>
          <li>支持课程的添加、删除和位置调整</li>
          <li>可以将课程拖出课程表删除</li>
          <li>支持移动端触摸操作</li>
          <li>课程表数据会自动保存在本地</li>
          <li>可以下载课程表为图片格式</li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ScheduleView'
}
</script>

<script setup>
import { ref, onMounted, watch, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Download, Delete, Back } from '@element-plus/icons-vue'
import html2canvas from 'html2canvas'

// 添加 router 实例
const router = useRouter()

// 课程数据
const courses = ref([
  { name: '语文', color: '#FF6B6B' },
  { name: '数学', color: '#4ECDC4' },
  { name: '英语', color: '#45B7D1' },
  { name: '音乐', color: '#FFA07A' },
  { name: '政治', color: '#9B59B6' },
  { name: '历史', color: '#F39C12' },
  { name: '体育', color: '#2ECC71' }
])

// 星期数据
const days = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']

// 课程表数据
const schedule = ref([
  { time: '上午', ...Object.fromEntries(days.map(day => [day, []])) },
  { time: '下午', ...Object.fromEntries(days.map(day => [day, []])) }
])

// 拖拽相关状态
const draggedItem = ref(null)
const dragSource = ref(null)
const isDragging = ref(false)

// 触摸相关状态
const touchStartTime = ref(0)
const touchStartPosition = ref({ x: 0, y: 0 })
const longPressThreshold = 500
const dragFeedback = ref(null)
let longPressTimer = null

// 拖拽开始
const dragStart = (event, course, row, day, index) => {
  draggedItem.value = { ...course }
  dragSource.value = row && day ? { row, day, index } : null
  event.dataTransfer.setData('text/plain', JSON.stringify(course))
}

// 放置处理
const onDrop = (event, row, day) => {
  event.preventDefault()
  event.target.classList.remove('dragover')
  const droppedData = JSON.parse(event.dataTransfer.getData('text/plain'))
  
  if (droppedData) {
    if (dragSource.value) {
      dragSource.value.row[dragSource.value.day].splice(dragSource.value.index, 1)
    }
    row[day].push(droppedData)
    schedule.value = JSON.parse(JSON.stringify(schedule.value))
    ElMessage.success('课程已移动')
  }
  
  draggedItem.value = null
  dragSource.value = null
}

// 全局拖拽结束处理
const handleGlobalDragEnd = (event) => {
  if (dragSource.value && !event.defaultPrevented) {
    dragSource.value.row[dragSource.value.day].splice(dragSource.value.index, 1)
    schedule.value = JSON.parse(JSON.stringify(schedule.value))
    ElMessage.success('课程已删除')
  }
  draggedItem.value = null
  dragSource.value = null
}

// 保存课程表
const saveSchedule = () => {
  localStorage.setItem('courseSchedule', JSON.stringify(schedule.value))
}

// 加载课程表
const loadSchedule = () => {
  const savedSchedule = localStorage.getItem('courseSchedule')
  if (savedSchedule) {
    schedule.value = JSON.parse(savedSchedule)
  }
}

// 行样式
const rowClassName = ({ rowIndex }) => {
  return rowIndex === 1 ? 'afternoon-row' : ''
}

// 拖拽相关事件处理
const onDragOver = (event) => event.preventDefault()

const onDragEnter = (event) => {
  const cell = event.currentTarget
  if (cell?.classList.contains('schedule-cell')) {
    cell.classList.add('dragover')
  }
}

const onDragLeave = (event) => {
  const cell = event.currentTarget
  if (cell?.classList.contains('schedule-cell') && !cell.contains(event.relatedTarget)) {
    cell.classList.remove('dragover')
  }
}

const onDragEnterCourse = (event) => {
  event.currentTarget.classList.add('dragover')
}

const onDragLeaveCourse = (event) => {
  event.currentTarget.classList.remove('dragover')
}

const onDragOverCourse = (event) => {
  event.preventDefault()
}

const onDropCourse = (event, row, day, index) => {
  event.preventDefault()
  event.stopPropagation()
  event.currentTarget.classList.remove('dragover')
  
  const droppedData = JSON.parse(event.dataTransfer.getData('text/plain'))
  if (droppedData) {
    if (dragSource.value) {
      dragSource.value.row[dragSource.value.day].splice(dragSource.value.index, 1)
    }
    row[day].splice(index, 0, droppedData)
    draggedItem.value = null
    dragSource.value = null
  }
}

// 下载课程表
const downloadSchedule = () => {
  const scheduleElement = document.getElementById('schedule-content')
  const cells = scheduleElement.querySelectorAll('.schedule-cell')
  const dragoverElements = scheduleElement.querySelectorAll('.dragover')
  
  cells.forEach(cell => cell.style.border = 'none')
  dragoverElements.forEach(element => element.classList.remove('dragover'))

  const scheduleWrapper = document.querySelector('.schedule-wrapper')
  const originalScrollLeft = scheduleWrapper.scrollLeft
  const originalScrollTop = scheduleWrapper.scrollTop
  scheduleWrapper.style.overflow = 'visible'

  html2canvas(scheduleElement, {
    scale: 2,
    useCORS: true,
    allowTaint: true,
    backgroundColor: '#ffffff'
  }).then(canvas => {
    const link = document.createElement('a')
    link.download = '课程表.png'
    link.href = canvas.toDataURL()
    link.click()

    cells.forEach(cell => cell.style.border = '1px solid #dcdfe6')
    dragoverElements.forEach(element => element.classList.add('dragover'))
    scheduleWrapper.style.overflow = 'auto'
    scheduleWrapper.scrollLeft = originalScrollLeft
    scheduleWrapper.scrollTop = originalScrollTop

    ElMessage.success('课程表已下载')
  })
}

// 清空课程表
const clearSchedule = () => {
  ElMessageBox.confirm(
    '确定要清空课程表吗？此操作不可逆。',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    schedule.value = [
      { time: '上午', ...Object.fromEntries(days.map(day => [day, []])) },
      { time: '下午', ...Object.fromEntries(days.map(day => [day, []])) }
    ]
    saveSchedule()
    ElMessage.success('课程表已清空')
  }).catch(() => {
    ElMessage.info('已取消清空操作')
  })
}

// 返回首页
const goToHomepage = () => {
  router.push('/')
}

// 触摸相关事件处理
const touchStart = (event, course, row, day, index) => {
  event.preventDefault()
  touchStartTime.value = Date.now()
  touchStartPosition.value = {
    x: event.touches[0].clientX,
    y: event.touches[0].clientY
  }
  draggedItem.value = { ...course }
  dragSource.value = row && day ? { row, day, index } : null

  longPressTimer = setTimeout(() => {
    const touchDuration = Date.now() - touchStartTime.value
    if (touchDuration >= longPressThreshold) {
      isDragging.value = true
      createDragFeedback(event.touches[0].clientX, event.touches[0].clientY)
      ElMessage.success('开始拖动')
    }
  }, longPressThreshold)
}

const touchMove = (event) => {
  if (isDragging.value) {
    event.preventDefault()
    const touch = event.touches[0]
    updateDragFeedback(touch.clientX, touch.clientY)
    highlightDropTarget(touch)
  } else {
    const moveX = event.touches[0].clientX - touchStartPosition.value.x
    const moveY = event.touches[0].clientY - touchStartPosition.value.y
    if (Math.sqrt(moveX * moveX + moveY * moveY) > 10) {
      clearTimeout(longPressTimer)
    }
  }
}

const touchEnd = (event) => {
  clearTimeout(longPressTimer)
  if (isDragging.value) {
    event.preventDefault()
    const touch = event.changedTouches[0]
    const targetElement = document.elementFromPoint(touch.clientX, touch.clientY)
    const cellElement = targetElement?.closest('.schedule-cell')

    if (cellElement) {
      const day = cellElement.dataset.day
      const time = cellElement.dataset.time
      const rowIndex = schedule.value.findIndex(r => r.time === time)

      if (rowIndex !== -1 && day) {
        if (dragSource.value) {
          dragSource.value.row[dragSource.value.day].splice(dragSource.value.index, 1)
        }
        
        if (!schedule.value[rowIndex][day]) {
          schedule.value[rowIndex][day] = []
        }
        
        schedule.value[rowIndex][day].push(draggedItem.value)
        schedule.value = JSON.parse(JSON.stringify(schedule.value))
        ElMessage.success('课程已移动')
      } else {
        ElMessage.warning('无效的放置位置')
      }
    } else if (dragSource.value) {
      dragSource.value.row[dragSource.value.day].splice(dragSource.value.index, 1)
      schedule.value = JSON.parse(JSON.stringify(schedule.value))
      ElMessage.success('课程已删除')
    }

    removeDragFeedback()
    isDragging.value = false
  }

  draggedItem.value = null
  dragSource.value = null
  document.querySelectorAll('.schedule-cell').forEach(cell => {
    cell.classList.remove('dragover')
  })
}

// 拖拽反馈相关
const createDragFeedback = (x, y) => {
  dragFeedback.value = document.createElement('div')
  dragFeedback.value.className = 'drag-feedback'
  dragFeedback.value.textContent = draggedItem.value.name
  dragFeedback.value.style.backgroundColor = draggedItem.value.color
  document.body.appendChild(dragFeedback.value)
  updateDragFeedback(x, y)
}

const updateDragFeedback = (x, y) => {
  if (dragFeedback.value) {
    dragFeedback.value.style.left = `${x}px`
    dragFeedback.value.style.top = `${y}px`
  }
}

const removeDragFeedback = () => {
  if (dragFeedback.value) {
    document.body.removeChild(dragFeedback.value)
    dragFeedback.value = null
  }
}

const highlightDropTarget = (touch) => {
  const elements = document.elementsFromPoint(touch.clientX, touch.clientY)
  const cellElement = elements.find(el => el.classList.contains('schedule-cell'))
  
  document.querySelectorAll('.schedule-cell').forEach(cell => {
    cell.classList.remove('dragover')
  })

  if (cellElement) {
    cellElement.classList.add('dragover')
  }
}

// 生命周期钩子
onMounted(() => {
  loadSchedule()
  document.addEventListener('dragend', handleGlobalDragEnd)
})

onUnmounted(() => {
  document.removeEventListener('dragend', handleGlobalDragEnd)
})

// 监听课程表变化
watch(schedule, saveSchedule, { deep: true })
</script>

<style lang="scss" scoped>
.schedule-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  overflow-y: auto;

  .schedule-container {
    max-width: 1200px;
    width: 96%;
    background-color: rgba(255, 255, 255, 0.95);
    border-radius: 20px;
    box-shadow: 0 15px 30px rgba(0, 0, 0, 0.2);
    padding: 30px;
    box-sizing: border-box;
    margin: 10px auto;

    h1 {
      text-align: center;
      color: #4a5568;
      font-size: 28px;
      margin-bottom: 30px;
      text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
    }

    .content-wrapper {
      display: flex;
      gap: 30px;
      margin-bottom: 30px;

      @media (max-width: 768px) {
        flex-direction: column;
      }

      .course-menu {
        width: 200px;
        flex-shrink: 0;

        @media (max-width: 768px) {
          width: 100%;
          display: flex;
          flex-wrap: wrap;
          gap: 10px;
          justify-content: center;
        }

        .course-item {
          padding: 10px;
          margin-bottom: 10px;
          border-radius: 8px;
          cursor: move;
          color: #ffffff;
          font-weight: bold;
          text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
          text-align: center;
          transition: all 0.3s ease;

          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
          }

          @media (max-width: 768px) {
            flex: 0 0 calc(33.33% - 10px);
            margin-bottom: 0;
          }
        }
      }

      .schedule-area {
        flex: 1;
        min-width: 0;

        .schedule-wrapper {
          overflow-x: auto;
          -webkit-overflow-scrolling: touch;
          margin-bottom: 20px;

          .schedule-table {
            min-width: 800px;
            border-collapse: separate;
            border-spacing: 0;

            :deep(.el-table__cell) {
              border-right: 1px solid #e4e4e4;
              vertical-align: top;
            }

            .schedule-cell {
              min-height: 100px;
              border: 1px solid #dcdfe6;
              padding: 5px;
              transition: all 0.3s ease;
              position: relative;
              display: flex;
              flex-direction: column;
              align-items: flex-start;
              justify-content: flex-start;

              &.dragover {
                border: 2px dashed #409EFF;
              }

              .course {
                width: 100%;
                padding: 8px;
                border-radius: 6px;
                margin-bottom: 5px;
                cursor: move;
                color: #ffffff;
                font-weight: bold;
                text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
                box-sizing: border-box;
                transition: all 0.3s ease;

                &:hover {
                  transform: translateY(-2px);
                  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
                }

                &.dragover {
                  border: 2px dashed #409EFF;
                }
              }
            }
          }
        }

        .button-group {
          display: flex;
          gap: 15px;
          justify-content: center;
          margin-top: 20px;

          .el-button {
            min-width: 120px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            padding: 12px 20px;
            font-size: 14px;
            border-radius: 8px;
            transition: all 0.3s ease;

            &:hover {
              transform: translateY(-2px);
              box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            }

            .el-icon {
              font-size: 16px;
            }
          }

          @media (max-width: 768px) {
            flex-direction: column;
            gap: 10px;

            .el-button {
              width: 100%;
            }
          }
        }
      }
    }

    .notes {
      margin-top: 40px;
      padding: 20px;
      background-color: #f0f5ff;
      border-radius: 12px;
      color: #606266;
      text-align: left;

      h3 {
        color: #409EFF;
        margin: 0 0 15px 0;
        font-size: 16px;
        text-align: left;
      }

      ul {
        margin: 0;
        padding-left: 0;
        list-style-type: none;
        text-align: left;

        li {
          margin-bottom: 12px;
          line-height: 1.6;
          position: relative;
          padding-left: 18px;
          text-align: left;

          &:before {
            content: "•";
            color: #409EFF;
            font-size: 18px;
            position: absolute;
            left: 0;
            top: -2px;
          }

          &:last-child {
            margin-bottom: 0;
          }
        }
      }
    }
  }
}

.drag-feedback {
  position: fixed;
  pointer-events: none;
  z-index: 1000;
  padding: 8px 12px;
  border-radius: 6px;
  color: white;
  font-weight: bold;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  opacity: 0.8;
  transform: translate(-50%, -50%);
}

@media (max-width: 480px) {
  .schedule-page {
    padding: 10px;

    .schedule-container {
      padding: 15px;
      border-radius: 15px;

      h1 {
        font-size: 24px;
        margin-bottom: 20px;
      }

      .content-wrapper {
        gap: 15px;

        .course-menu {
          .course-item {
            padding: 8px;
            font-size: 13px;
          }
        }
      }

      .notes {
        padding: 15px;
        margin-top: 30px;

        h3 {
          font-size: 15px;
        }

        ul li {
          font-size: 13px;
          margin-bottom: 8px;
        }
      }
    }
  }
}
</style>

